<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>系统管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
</head>

<body>
    <div class="layui-container">
        <div class="header" style="margin-top: 15px;">
            <h1 style="text-align: center;">系统管理后台</h1>
        </div>
        <div class="layui-tabs layui-hide-v" id="adminTabs" lay-options="{closable: false}">
            <div>
                <span id="currentTime" style="color: #666;"></span>
            </div>
            <ul class="layui-tabs-header">
                <li lay-id="tabUser" lay-closable="false">用户管理</li>
                <li lay-id="tabSessions" lay-closable="false">会话管理</li>
                <li lay-id="tabProjects" lay-closable="false">项目管理</li>
                <li lay-id="tabStats" lay-closable="false">系统统计</li>
            </ul>

            <div class="layui-tabs-body">
                <div class="layui-tabs-item layui-show">
                    <table id="userTable" lay-filter="userTable"></table>
                    <script type="text/html" id="ID-table-user-pagebar">
                        <div class="layui-btn-container">
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="refreshAll()"><i
                        class="layui-icon layui-icon-refresh"></i>刷新数据</button>
                            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="addUser()"><i
                        class="layui-icon layui-icon-add-1"></i>添加用户</button>
                        </div>
                    </script>
                </div>

                <div class="layui-tabs-item">
                    <div class="layui-card">
                        <div class="layui-card-body">
                            <div class="layui-form">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">用户筛选</label>
                                    <div class="layui-input-inline">
                                        <input type="text" id="userFilter" placeholder="用户ID" class="layui-input">
                                    </div>
                                    <button class="layui-btn" onclick="loadSessions()">查询</button>
                                </div>
                            </div>

                            <table id="sessionTable" lay-filter="sessionTable"></table>
                        </div>
                    </div>
                </div>

                <div class="layui-tabs-item">
                    <div class="layui-form" style="flex-shrink: 0; padding-bottom: 10px;">
                        <div class="layui-row" style="display: flex; align-items: center;">
                            <div>
                                建设单位
                            </div>
                            <div style="flex:1; margin-left:10px; margin-right: 10px;;">
                                <select name="orgName" lay-verify="required" id="orgSelect" style="width: 180px">
                                    <option value="">加载中...</option>
                                </select>
                            </div>
                            <div style="flex:1; margin-right: 10px;">
                                <input type="text" name="search" id="search-input" placeholder="输入工程编码/名称"
                                    class="layui-input" lay-verify="search" style="width:300px;">
                            </div>
                            <div style="width:100px;">
                                <button class="layui-btn layui-btn-sm" id="btn-search" type="button">搜索</button>
                            </div>
                        </div>
                    </div>
                    <!-- 项目表格 -->
                    <table id="projectTable" lay-filter="projectTable"></table>
                </div>

                <!-- 系统统计面板 -->
                <div class="layui-tabs-item">
                    <div id="statsPanel">
                        <!-- 默认加载状态 -->
                        <div class="layui-row">
                            <div class="layui-col-md4">
                                <div class="layui-card">
                                    <div class="layui-card-header">用户统计</div>
                                    <div class="layui-card-body" style="font-size: 24px; color: #1E9FFF;">
                                        <div class="layui-admin-loading">加载中...</div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md4">
                                <div class="layui-card">
                                    <div class="layui-card-header">项目统计</div>
                                    <div class="layui-card-body" style="font-size: 24px; color: #5FB878;">
                                        <div class="layui-admin-loading">加载中...</div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md4">
                                <div class="layui-card">
                                    <div class="layui-card-header">活跃会话</div>
                                    <div class="layui-card-body" style="font-size: 24px; color: #FFB800;">
                                        <div class="layui-admin-loading">加载中...</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>


    <!-- 添加用户管理工具栏模板 -->
    <script type="text/html" id="userToolbar">
        <div class="layui-btn-group">
            <button class="layui-btn layui-btn-xs" lay-event="edit">编辑</button>
            <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="freeze">冻结</button>
        </div>
    </script>
    <!-- 会话操作工具栏模板 -->
    <script type="text/html" id="sessionToolbar">
        <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="close">终止</button>
    </script>

    <!-- 项目操作工具栏模板 -->
    <script type="text/html" id="projectToolbar">
        <button class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</button>
    </script>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/js/auth-utils.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/utils.js"></script>
    <script>
        layui.use(['table', 'element', 'tabs', 'util', 'jquery'], function () {
            var table = layui.table;
            var element = layui.element;
            var tabs = layui.tabs;
            var util = layui.util;
            var bsm_utils = layui.bsm_utils;
            var $ = layui.$;

            var TABS_ID = 'adminTabs';
            var projectTableData = []; // 存储所有数据
            var isComposing = false; // 输入法状态

            // 存储表格实例和初始化状态
            var tableState = {
                userTable: null,
                sessionTable: null,
                userInitialized: false,
                sessionInitialized: false,
                statsInitialized: false,
                projectTableInitialized: false,
            };

            // Tab切换事件监听
            tabs.on(`afterChange(${TABS_ID})`, function (data) {
                console.log('切换到Tab:', data.index);
                switch (data.index) {
                    case 0: // 用户管理
                        if (!tableState.userInitialized) {
                            initUserTable();
                            tableState.userInitialized = true;
                        }
                        break;
                    case 1: // 会话管理
                        if (!tableState.sessionInitialized) {
                            initSessionTable();
                            tableState.sessionInitialized = true;
                        }
                        break;
                    case 2: // 项目管理
                        if (!tableState.projectTableInitialized) {
                            initProjectTable();
                            tableState.projectTableInitialized = true;
                        }
                        break;
                    case 3: // 系统统计
                        if (!tableState.statsInitialized) {
                            initStatsPanel();
                            tableState.statsInitialized = true;
                        }
                        break;
                }
            });

            // 初始化用户表格
            function initUserTable() {
                http.get(API_CONFIG.ADMIN.USERS + '?limit=1000')
                    .then(function (res) {
                        tableState.userTable = table.render({
                            elem: '#userTable',
                            data: res.data,
                            page: {
                                layout: ['limit', 'count', 'prev', 'page', 'next'],
                                first: false,
                                last: false
                            },
                            limits: [10, 20, 50, 100],
                            limit: 10,
                            maxHeight: 'full-180',
                            pagebar: '#ID-table-user-pagebar',
                            cols: [[
                                { type: 'numbers', title: '序号', width: "60", align: 'center' },
                                { field: 'user_id', title: '账号', width: 200 },
                                { field: 'user_name', title: '姓名', width: 200 },
                                { field: 'org_litename', title: '组织名称', width: 200 },
                                {
                                    field: 'created_at', title: '创建时间', width: 300, templet: function (d) {
                                        return util.toDateString(d.created_at);
                                    }
                                },
                                { field: "session_count", title: "会话数", width: 80 },
                                { fixed: 'right', title: '操作', align: 'center', toolbar: '#userToolbar' }
                            ]]
                        });
                    })
                    .catch(function (err) {
                        layer.msg('加载用户数据失败');
                    });
            }

            // 初始化会话表格
            function initSessionTable() {
                http.get(API_CONFIG.ADMIN.SESSIONS + '?limit=1000')
                    .then(function (res) {
                        tableState.sessionTable = table.render({
                            elem: '#sessionTable',
                            data: res.data,
                            page: true,
                            limits: [10, 20, 50],
                            limit: 10,
                            height: 500,
                            cols: [[
                                { type: 'numbers', title: '序号', width: "60", align: 'center' },
                                { field: 'user_id', title: '用户账号', width: 80 },
                                { field: 'ip_address', title: '会话IP', width: 120 },
                                { field: 'login_time', title: '登录时间', width: 300 },
                                { field: 'last_active', title: '最后活动', width: 300 },
                                {
                                    field: 'status', title: '状态', width: 80, templet: function (d) {
                                        return d.status === 1 ? '活跃' : '关闭';
                                    }
                                },
                                { fixed: 'right', title: '操作', toolbar: '#sessionToolbar', width: 100 }
                            ]]
                        });
                    })
                    .catch(function (err) {
                        layer.msg('加载会话数据失败');
                    });
            }

            // 初始化项目表格
            function initProjectTable() {
                http.get(API_CONFIG.ADMIN.PROJECTS, { org_code: '', design_type: API_CONFIG.DESIGNTYPE.All })
                    .then(function (res) {
                        tableState.projectTable = table.render({
                            elem: '#projectTable',
                            data: res.data,
                            page: true,
                            fixed: true,
                            maxHeight: 'full-180',
                            cols: [[
                                { type: 'numbers', title: '序号', width: 60 },
                                { field: 'design_code', title: '设计编码', width: 150 },
                                { field: 'name', title: '项目名称' },
                                {
                                    field: 'project_state', title: '状态', width: 60, align: 'center', templet: function (d) {
                                        if (d.project_state === API_CONFIG.PROJECT_STATE.ToBudget) {
                                            return '设计';
                                        } else if (d.project_state === API_CONFIG.PROJECT_STATE.ToAccept) {
                                            return '验收';
                                        } else if (d.project_state === API_CONFIG.PROJECT_STATE.ToAudit) {
                                            return '审计';
                                        } else {
                                            return '未知';
                                        }
                                    }
                                },
                                { fixed: 'right', title: '操作', toolbar: '#projectToolbar', width: 100 }
                            ]]
                        });

                        // 存储数据用于搜索筛选
                        projectTableData = res.data || [];

                        // 绑定搜索事件
                        bindSearchEvents();
                    })
                    .catch(function (err) {
                        layer.msg('加载项目数据失败');
                        console.error('项目数据加载错误:', err);
                    });
            }

            // 绑定搜索相关事件
            function bindSearchEvents() {
                // 输入法状态监听
                $('#search-input')
                    .on('compositionstart', function () {
                        isComposing = true;
                    })
                    .on('compositionend', function () {
                        isComposing = false;
                        var keyword = $(this).val();
                        filterProjectData(keyword);
                    })
                    .on('input', function () {
                        if (!isComposing) {
                            var keyword = $(this).val();
                            filterProjectData(keyword);
                        }
                    });

                // 搜索按钮点击事件
                $('#btn-search').on('click', function () {
                    var keyword = $('#search-input').val();
                    filterProjectData(keyword);
                });

                // 回车键搜索
                $('#search-input').on('keydown', function (e) {
                    if (e.keyCode === 13) {
                        var keyword = $(this).val();
                        filterProjectData(keyword);
                    }
                });

                // 移除了双击行事件
            }

            // 筛选项目函数
            function filterProjectData(keyword = '') {
                if (!projectTableData.length) return;

                var filteredData;
                if (keyword.trim() === '') {
                    filteredData = projectTableData;
                } else {
                    filteredData = projectTableData.filter(item => {
                        var matchCode = item.design_code && item.design_code.toString().includes(keyword);
                        var matchName = item.project_name && item.project_name.toString().includes(keyword);
                        return matchCode || matchName;
                    });
                }

                table.reload('projectTable', {
                    data: filteredData,
                    page: false
                });
            }

            // 初始化统计面板 - 简化版本
            function initStatsPanel() {
                // 显示加载状态
                updateStatsPanel('loading');

                fetch(API_CONFIG.ADMIN.STATS, {
                    headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
                }).then(res => res.json())
                    .then(stats => {
                        if (stats && stats.data) {
                            updateStatsPanel('success', stats.data);
                        } else {
                            updateStatsPanel('error', '数据格式错误');
                        }
                    })
                    .catch(function (err) {
                        console.error('统计信息加载失败:', err);
                        updateStatsPanel('error', '加载失败');
                    });
            }

            // 更新统计面板显示
            function updateStatsPanel(status, data) {
                const statsPanel = document.getElementById('statsPanel');
                const cards = statsPanel.querySelectorAll('.layui-card-body');

                if (status === 'loading') {
                    // 保持默认的加载中状态
                    return;
                }

                if (status === 'success' && data) {
                    // 更新数据
                    if (cards[0]) cards[0].innerHTML = data.user_count || '0';
                    if (cards[1]) cards[1].innerHTML = data.project_count || '0';
                    if (cards[2]) cards[2].innerHTML = data.active_sessions || '0';
                } else if (status === 'error') {
                    // 显示错误状态
                    cards.forEach(card => {
                        card.innerHTML = '<span style="color: #FF5722; font-size: 14px;">加载失败</span>';
                    });
                }
            }

            // 用户表格工具条事件
            table.on('tool(userTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    openUserEditPopup(data);
                } else if (obj.event === 'freeze') {
                    layer.confirm('确定冻结用户账号？', function (index) {
                        layer.msg('冻结用户账号: ' + data.user_id);
                        layer.close(index);
                    });
                }
            });

            // 会话表格工具条事件
            table.on('tool(sessionTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'close') {
                    const currentUser = window.authUtils.getCurrentUser();
                    sid = bsm_utils.getSessionId();
                    if (sid === data.session_id) {
                        layer.msg('不能终止当前会话，请使用登出功能', { icon: 2 });
                    }
                    else {
                        layer.confirm('确定终止会话？', function (index) {
                            http.delete(API_CONFIG.ADMIN.SESSIONS + '/' + data.session_id)
                                .then(function (res) {
                                    layer.msg('会话终止成功');
                                    // 重新获取会话数据
                                    http.get(API_CONFIG.ADMIN.SESSIONS + '?limit=1000')
                                        .then(function (newRes) {
                                            table.reload('sessionTable', {
                                                data: newRes.data
                                            });
                                        });
                                })
                                .catch(function (err) {
                                    if (err.code === 404) {
                                        layer.msg('会话不存在或已被终止');
                                    } else if (err.code === 403) {
                                        layer.msg('权限不足，无法终止该会话');
                                    }
                                })
                                .finally(function () {
                                    layer.close(index);
                                });
                        });
                    }
                }
            });

            // 项目表格工具条事件
            table.on('tool(projectTable)', function (obj) {
                var data = obj.data;
                if (obj.event === 'delete') {
                    layer.confirm('确定删除项目？', function (index) {
                        console.log("删除项目", data.design_code, data.project_state)
                        http.delete(API_CONFIG.ADMIN.PROJECTS + '/' + data.design_code, {
                            params: {
                                design_type: data.project_state
                            }
                        })
                            .then(function (res) {
                                layer.msg('项目删除成功');
                                // 重新获取项目数据
                                http.get(API_CONFIG.ADMIN.PROJECTS, { org_code: '', design_type: API_CONFIG.DESIGNTYPE.All })
                                    .then(function (newRes) {
                                        table.reload('projectTable', {
                                            data: newRes.data
                                        });
                                    });
                            })
                            .catch(function (err) {
                                if (err.code === 404) {
                                    layer.msg('项目不存在或已被删除');
                                } else if (err.code === 403) {
                                    layer.msg('权限不足，无法删除该项目');
                                }
                            })
                            .finally(function () {
                                layer.close(index);
                            });
                    });
                }
            })

            // 
            // 默认初始化第一个Tab（用户管理）
            initUserTable();
            tableState.userInitialized = true;

            LoadOrgList();

            // function LoadOrgList() {
            //     http.get(API_CONFIG.ENDPOINTS.GET_ORG_LIST)
            //         .then(function (res) {
            //             var orgList = res.data || [];
            //             var orgSelect = document.getElementById('org_code');
            //             orgSelect.innerHTML = '';
            //             orgList.forEach(function (org) {
            //                 var option = document.createElement('option');
            //                 option.value = org.org_code;
            //                 option.textContent = org.org_name;
            //                 orgSelect.appendChild(option);
            //             });
            //         })
            //         .catch(function (err) {
            //             layer.msg('获取组织列表失败');
            //         });
            // }

            // 全局函数定义

            function LoadOrgList() {
                http.get(API_CONFIG.ENDPOINTS.GET_ORG_LIST)
                    .then(function (res) {
                        console.log('组织列表返回数据:', res); // 调试用

                        var orgList = res.data || [];
                        var orgSelect = document.getElementById('orgSelect'); // 修正ID

                        if (!orgSelect) {
                            console.error('未找到组织选择框元素');
                            return;
                        }

                        // 清空现有选项
                        orgSelect.innerHTML = '';

                        // 添加默认选项
                        var defaultOption = document.createElement('option');
                        defaultOption.value = '';
                        defaultOption.textContent = '全部组织';
                        orgSelect.appendChild(defaultOption);

                        // 添加组织选项
                        orgList.forEach(function (org) {
                            var option = document.createElement('option');
                            option.value = org.org_code || org.value || org.id;
                            option.textContent = org.org_name || org.name || org.text;
                            orgSelect.appendChild(option);
                        });

                        // 重新渲染Layui选择框
                        layui.form.render('select');

                        console.log('组织列表加载完成，共', orgList.length, '个组织');
                    })
                    .catch(function (err) {
                        console.error('获取组织列表失败:', err);
                        layer.msg('获取组织列表失败: ' + (err.msg || '网络错误'));

                        // 设置错误状态
                        var orgSelect = document.getElementById('orgSelect');
                        if (orgSelect) {
                            orgSelect.innerHTML = '<option value="">加载失败，请刷新</option>';
                            layui.form.render('select');
                        }
                    });
            }

            window.addUser = function () {
                layer.open({
                    type: 2,
                    title: '添加用户',
                    content: '/admin/addUser',
                    area: ['500px', '400px'],
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {
                        var submit = layero.find('iframe').contents().find(".layui-btn.layuiadmin-btn-useradmin");
                        submit.click();
                    },
                    end: function () {
                        window.refreshAll();
                    }
                });
            }

            window.refreshAll = function () {
                // 显示加载中
                var loading = layer.load(1);

                // 重新初始化所有表格和面板
                Promise.all([
                    new Promise(resolve => {
                        initUserTable();
                        setTimeout(resolve, 500);
                    }),
                    new Promise(resolve => {
                        initSessionTable();
                        setTimeout(resolve, 500);
                    }),
                    new Promise(resolve => {
                        initStatsPanel();
                        setTimeout(resolve, 500);
                    }),
                    new Promise(resolve => {
                        // 如果项目管理已初始化，则刷新数据
                        if (tableState.projectTableInitialized) {
                            http.get(API_CONFIG.ADMIN.PROJECTS + '?limit=1000')
                                .then(function (res) {
                                    projectTableData = res.data || [];
                                    table.reload('projectTable', {
                                        data: projectTableData
                                    });
                                });
                        }
                        setTimeout(resolve, 500);
                    })
                ]).then(() => {
                    layer.close(loading);
                    layer.msg('数据刷新完成', { icon: 1 });
                });
            }

            window.loadSessions = function () {
                var userId = document.getElementById('userFilter').value;
                var url = API_CONFIG.ADMIN.SESSIONS + (userId ? '?user_id=' + userId + '&limit=1000' : '?limit=1000');

                var loading = layer.load(1);

                http.get(url)
                    .then(function (res) {
                        layer.close(loading);
                        table.reload('sessionTable', {
                            data: res.data
                        });
                        var msg = userId ?
                            `用户 ${userId} 的会话查询完成，找到 ${res.data.length} 条记录` :
                            `所有会话查询完成，共 ${res.data.length} 条记录`;
                        layer.msg(msg);
                    })
                    .catch(function (err) {
                        layer.close(loading);
                        layer.msg('查询失败: ' + (err.msg || err.message));
                    });
            }

            window.updateCurrentTime = function () {
                var now = new Date();
                var timeString = now.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                });
                document.getElementById('currentTime').textContent = '当前时间: ' + timeString;
            }

            // 添加用户编辑相关函数
            window.openUserEditPopup = function (userData) {
                var title = userData ? '编辑用户 - ' + userData.user_name : '添加用户';
                var url = '/admin/user-edit-popup' + (userData ? '?id=' + userData.user_id : '');

                // 注意：这里需要确保utils对象存在，或者使用layer.open
                layer.open({
                    type: 2,
                    title: title,
                    content: url,
                    area: ['800px', '600px'],
                    maxmin: true,
                    resize: false
                });
            };

            // 页面加载完成后开始更新时间
            document.addEventListener('DOMContentLoaded', function () {
                updateCurrentTime();
                setInterval(updateCurrentTime, 1000);
            });
        });    
    </script>
</body>

</html>